import React, { useEffect } from "react"
import NavItem from "./NavItem"
import "./index.less"
import { useAppSelector } from "@/store"
import { shallowEqual, useDispatch } from "react-redux"
import { useLocation, useNavigate } from "react-router-dom"
import { findRoute } from "@/utils"
import { constanceRoutes, anyRoutes } from "@/router/routers"
import {
	addTagsAciton,
	changeIndexAction,
	removeTagAction,
} from "@/store/modules/menus"
const Navs: React.FC = () => {
	const dispatch = useDispatch()
	const { tags, current, dynamicRouteList } = useAppSelector(
		(state) => ({
			tags: state.menusStore.tags,
			current: state.menusStore.current,
			dynamicRouteList: state.userStore.dynamicRouteList,
		}),
		shallowEqual,
	)
	const { pathname } = useLocation()
	const navigate = useNavigate()
	useEffect(() => {
		const dynamicRoutes = JSON.parse(dynamicRouteList)
		const routerList = constanceRoutes.concat(dynamicRoutes, anyRoutes)
		const route = findRoute(pathname, routerList)
		console.log("route", route)
		if (Object.keys(route).length > 0) {
			const obj = {
				title: route.meta?.title,
				url: route.path,
				icon: route.meta?.icon,
				closeable: true,
			}
			dispatch(addTagsAciton(obj))
			dispatch(changeIndexAction(obj))
		}
	}, [dynamicRouteList, pathname])
	useEffect(() => {
		navigate(current.url)
	}, [current])
	const close = (item: any) => {
		console.log(item)
		const index = tags.findIndex((it) => it.url === item.url)
		dispatch(changeIndexAction(tags[index - 1]))
		dispatch(removeTagAction(item))
	}
	return (
		<ul className="navs">
			{tags.map((it) => {
				return <NavItem closeItem={close} key={it.url} {...it}></NavItem>
			})}
		</ul>
	)
}

export default Navs
